import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Menu, Icon } from 'antd';
import { Link } from 'dva/router';
import { autobind } from 'core-decorators';
import _ from 'lodash';
import { helper } from '../utils';
import pathToRegexp from 'path-to-regexp';
import { connect } from 'dva';

import THFXIcon from '../components/common/THFXIcon';


const mapStateToProps = state => ({
	userInfo: state.login.userInfo,
});
const mapDispatchToProps = {
	queryUser: query => ({
		type: 'login/queryUser',
	}),
};

@connect(mapStateToProps,mapDispatchToProps)
class Menus extends Component {

	constructor(props) {
		super(props);
	}
	static propTypes = {
		userInfo: PropTypes.object.isRequired,
	}
	componentWillMount() {
		const { userInfo,queryUser } = this.props;
		const userMenus = userInfo.menus;
		if(_.isEmpty(userMenus)){
			queryUser();
		}

		this.levelMap = {};
		this.menus=userMenus||[];
		this.menuTree = [];

	}
 componentWillReceiveProps(nextProps) {
		const { userInfo } = nextProps;
		const { queryUser } = this.props;
		const userMenus = userInfo.menus&&userInfo.menus.map(item=>({
			key: item.menuCode,
			id: item.menuCode,
			icon:item.icon,
			bpid: item.parentMenu&&item.parentMenu!=''?item.parentMenu:null,
			mpid: item.parentMenu&&item.parentMenu!=''?item.parentMenu:null,
			name: item.menuText,
			router: item.menuURL&&item.menuURL!=''?item.menuURL:null,
		}))||[];
		this.menus=userMenus;
		this.menuTree = helper.arrayToTree(userMenus, 'id', 'mpid');
	}

	// 递归生成菜单
	getMenus(menuTreeN, siderFoldN) {
		return menuTreeN.map((item) => {
			if (item.children) {
				if (item.mpid) {
					this.levelMap[item.id] = item.mpid;
				}
				return (
					<Menu.SubMenu
						key={item.id}
						title={<span>
							{item.icon && <THFXIcon type={item.icon} />}
							{(!siderFoldN || this.menuTree.indexOf(item) < 0) && item.name}
						</span>}
					>
						{this.getMenus(item.children, siderFoldN)}
					</Menu.SubMenu>
				);
			}
			return (
				<Menu.Item key={item.id}>
					<Link to={item.router}>
						{item.icon && <THFXIcon type={item.icon} />}
						{(!siderFoldN || this.menuTree.indexOf(item) < 0) && item.name}
					</Link>
				</Menu.Item>
			);
		});
	}

	// 保持选中
	getAncestorKeys(key) {
		const map = {};
		const getParent = (index) => {
			const result = [String(this.levelMap[index])];
			if (this.levelMap[result[0]]) {
				result.unshift(getParent(result[0])[0]);
			}
			return result;
		};
		for (const index in this.levelMap) {
			if ({}.hasOwnProperty.call(this.levelMap, index)) {
				map[index] = getParent(index);
			}
		}
		return map[key] || [];
	}

	@autobind
	onOpenChange(openKeys) {
		const { navOpenKeys, changeOpenKeys } = this.props;
		const latestOpenKey = openKeys.find(key => !(navOpenKeys&&navOpenKeys.indexOf(key) > -1));
		const latestCloseKey = navOpenKeys&&navOpenKeys.find(key => !(openKeys.indexOf(key) > -1));
		let nextOpenKeys = [];
		if (latestOpenKey) {
			nextOpenKeys = this.getAncestorKeys(latestOpenKey).concat(latestOpenKey);
		}
		if (latestCloseKey) {
			nextOpenKeys = this.getAncestorKeys(latestCloseKey);
		}
		changeOpenKeys(nextOpenKeys);
	}

	getPathArray(array, current, pid, id) {
		const result = [String(current[id])];
		const getPath = (item) => {
			if (item && item[pid]) {
				result.unshift(String(item[pid]));
				getPath(helper.queryArray(array, item[pid], id));
			}
		};
		getPath(current);
		return result;
	}

	render() {
		const { darkTheme, siderFold, navOpenKeys, location, handleClickNavMenu } = this.props;
		const menuProps = !siderFold ? {
			onOpenChange: this.onOpenChange,
			openKeys: navOpenKeys,
		} : {};

		// 寻找选中路由
		let currentMenu;
		let defaultSelectedKeys;
		for (const item of this.menus) {
			if (item.router && pathToRegexp(item.router).exec(location.pathname)) {
				currentMenu = item;
				break;
			}
		}

		if (currentMenu) {
			defaultSelectedKeys = this.getPathArray(this.menus, currentMenu, 'mpid', 'id');
		}

		return (
			<Menu
				{...menuProps}
				mode={siderFold ? 'vertical' : 'inline'}
				theme={darkTheme ? 'dark' : 'light'}
				onClick={handleClickNavMenu}
				defaultSelectedKeys={defaultSelectedKeys}
			>
				{this.getMenus(this.menuTree, siderFold)}
			</Menu>
		);
	}
}

Menus.propTypes = {
	userInfo: PropTypes.object.isRequired,
	siderFold: PropTypes.bool,
	darkTheme: PropTypes.bool,
	location: PropTypes.object,
	isNavbar: PropTypes.bool,
	handleClickNavMenu: PropTypes.func,
	navOpenKeys: PropTypes.array,
	changeOpenKeys: PropTypes.func,
};

export default Menus;
